package com.hmall.trade.listener;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.trade.constants.MQConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class OrderDelayListener {

    private final IOrderService orderService;
    private final PayClient payClient;

    //需要装插件
//    @RabbitListener(bindings = @QueueBinding(
//            value = @Queue(name = MQConstants.DELAY_ORDER_QUEUE_NAME, durable = "true"),
//            exchange = @Exchange(name = MQConstants.DELAY_EXCHANGE_NAME,delayed =" true"),
//            key = MQConstants.DELAY_ORDER_KEY
//    ))
    public void listenOrderDelaySuccess(Long orderId){
        //1查询订单
        Order order = orderService.getById(orderId);
        //2检测订单状态
        if (order == null || order.getStatus()!=1){
            //订单不存在或者已支付
            return;

        }

        //3未支付，需要查询支付流水状态
        PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);

        //4判断是否支付
        if (payOrderDTO != null && payOrderDTO.getStatus() == 3){
            //4.1已支付，标志订单为已支付
            orderService.markOrderPaySuccess(orderId);
        }else {
            //4.2未支付，取消订单，恢复库存
            orderService.cancelOrder(orderId);
        }







    }
}
